<?php

class Imageutil {
  static $base_path;
  public static function getBasePath() {
    if (self::$base_path!=null) return self::$base_path; else {
      return self::$base_path = dirname(__FILE__);
    }
  }

  public static function convertImage($source, $dest, $size, $extra_param='') {
    if (substr($source, 0, 7)!='http://') if (!file_exists($source)) return false;
    $img_cmd = self::getBasePath() . '/convert/convert.exe';
    //if (substr($source, 0, 7)!='http://') chmod($source, 0777);
    $dest_dir = dirname($dest);
    if (!file_exists($dest_dir)) mkdir($dest_dir, 0777, true);
    $command = "$img_cmd ".escapeshellarg($source)." -quality 60 -thumbnail $size\\> $extra_param " .
      " " . escapeshellarg($dest);
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => array("pipe", "w"),
    );
    $process = proc_open($command, $descriptorspec, $pipes);

    $log_file = '/tmp/convert.log';
    error_log($command."\n", 3, $log_file);

    if (is_resource($process)) {
      $ret = true;
      while (!feof($pipes[2])) {
        $line = trim(fgets($pipes[2],1024));
        error_log($line, 3, $log_file);
      }
      fclose($pipes[2]);
      proc_close($process);
      return true;
    }
    return false;
  }

  public static function getImageSize($fileName) {
    $length = strlen($fileName);
    $width = null;
    $height = null;
    $command = "/usr/bin/identify -format %wx%h\\n " . escapeshellarg($fileName);
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    );
    $process = proc_open($command, $descriptorspec, $pipes);

    if (is_resource($process)) {
      $ret = true;
      while (!feof($pipes[1])) {
        $line = trim(fgets($pipes[1],1024));
        if (preg_match('@Improper image header@', $line)) $ret = false;
        if (preg_match('@Not a JPEG file@', $line)) $ret = false;
        if (preg_match('@no decode delegate for this image format@', $line)) $ret = false;
        if ($line!=null) {
          if ($width == null && preg_match('@([0-9]+)x([0-9]+)@', $line, $size)) {
            $width = intval($size[1]);
            $height = intval($size[2]);
          }
        }
      }
      fclose($pipes[1]);
      proc_close($process);
    } else $ret = false;
    return array($width, $height);
  }


  public static function cropImage($source, $dest, $w, $h, $extra_param='') {
    if (substr($source, 0, 7)!='http://') if (!file_exists($source)) return false;

    $size = self::getImageSize($source);
    if (!$size) return false;
    list($width, $height) = $size;
    $sx = $width/$w;
    $sy = $height/$h;

    if ($sx>$sy) $sx = $sy;
    $sw = intval($w*$sx);
    $sh = intval($h*$sx);

    if ($sw<$width) {
      $x = intval(($width-$sw)/2);
      $extra = "-crop {$sw}x{$sh}+$x+0";
    } else if ($sh<$height) {
      $extra = "-crop {$sw}x{$sh}+0+0";
    } else {
      $extra = '';
    }

    $img_cmd = '/usr/bin/convert';
    $dest_dir = dirname($dest);
    if (!file_exists($dest_dir)) mkdir($dest_dir, 0777, true);
    $command = "$img_cmd ".escapeshellarg($source)." $extra -quality 60 -thumbnail {$w}x{$h} $extra_param " .
      " " . escapeshellarg($dest);
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => array("pipe", "w"),
    );
    $process = proc_open($command, $descriptorspec, $pipes);

    $log_file = '/tmp/convert.log';
    error_log($command."\n", 3, $log_file);

    if (is_resource($process)) {
      $ret = true;
      while (!feof($pipes[2])) {
        $line = trim(fgets($pipes[2],1024));
        error_log($line, 3, $log_file);
      }
      fclose($pipes[2]);
      proc_close($process);
      return true;
    }
    return false;
  }


  public static function joinImage($images, $dest, $size) {
    $img_cmd = self::getBasePath() . '/convert/montage.exe';
    $dest_dir = dirname($dest);
    if (!file_exists($dest_dir)) mkdir($dest_dir, 0777, true);

    $source = '';
    foreach ($images as $image) $source .= escapeshellarg($image).' ';
    $count = count($images);

    $command = "$img_cmd  -resize $size+0+0 -geometry +0+0 -tile {$count}x1 -quality 60 ".$source.
      escapeshellarg($dest);
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => array("pipe", "w"),
    );
    $process = proc_open($command, $descriptorspec, $pipes);

    $log_file = '/tmp/montage.log';
    error_log($command."\n", 3, $log_file);

    if (is_resource($process)) {
      $ret = true;
      while (!feof($pipes[2])) {
        $line = trim(fgets($pipes[2],1024));
        error_log($line, 3, $log_file);
      }
      fclose($pipes[2]);
      proc_close($process);
      return true;
    }
    return false;
  }
}

